home account info subscribe login search FAQ/help site map contact us


 
Brief Full
 Advanced
      Search
 Search Tips
To access the contents, click the chapter and section titles.

Bug Proofing Visual Basic: A Guide to Error Handling and Prevention
(Publisher: John Wiley & Sons, Inc.)
Author(s): Rod Stephens
ISBN: 0471323519
Publication Date: 11/01/98

Search this book:
 
Previous Table of Contents Next


The right versions of the functions can also make the code run more quickly. If the data types of the input and result variables do not match the type of the function, Visual Basic may need to perform data type conversions before and after calling the function. In the following code fragment, the variables s1 and s2 are both strings. Left$ returns a string value while Left returns a variant. In one test, the statement using Left took more than 1.5 times as long as the statement that uses Left$.

Dim s1 As String
Dim s2 As String

    ‘ Initialize s1.
        :
    s2 = Left$(s1, 12)
    s2 = Left(s1, 12)

Use the proper versions of these functions so the data types of the results are obvious.

Open and Close Files in the Same Routine

If a single routine opens and closes a file, it is easy to verify that the file is being properly closed. With a little reading, it is obvious whether the routine exits without closing the file.

On the other hand, if one routine opens the file and another closes it at some later time, it can be difficult to tell when and if the file is closed. The situation may be even more complicated if the file can be opened and closed in several different routines.

Unless the program needs to keep a file open for a long time, open and close it in the same routine. Keep the routine short and simple so it is easy to understand. Invoke other routines to perform elaborate file processing if necessary.

The following code opens a file, calls the ReadData subroutine to read data from the file, and then closes the file. Putting the complex data reading code in subroutine ReadData allows this routine to be short and simple, even with its error handling code.

‘ Load data from a file.
Private Sub LoadData(file_name As String)
Dim fnum As Integer

    ‘ Open the file.
    On Error GoTo OpenError
    fnum = FreeFile
    Open file_name For Input As fnum

    ‘ Read the data.
    On Error GoTo ReadError
    ReadData fnum

    ‘ Close the file.
CloseFile:
    On Error GoTo 0
    Close fnum

    Exit Sub

OpenError:
    MsgBox “Error” & Str$(Err.Number) & _
        “ opening file.” & vbCrLf & _
        Err.Description
    Exit Sub

ReadError:
    MsgBox “Error” & Str$(Err.Number) & _
        “ reading data.” & vbCrLf & _
        Err.Description
    Resume CloseFile
End Sub

Put Separate Commands on Separate Lines

Do not use Visual Basic’s command separator colon (:) to put more than one command on the same line. This can be confusing and is almost never necessary. It makes the code harder to read and gives no real benefit. It makes no appreciable difference in the speed of the code.

If your code window is too narrow to display the entire line, it may not be obvious that other commands follow to the right of the colon. Someone who reads the code and fails to notice the other commands cannot possibly understand the routine correctly.

One situation in which it may be tempting to put multiple commands on a single line is in a single-line If statement, as shown in the following code.

If NumEmployees < 10 Then BuildEmployeeReport : 
ShowEmployeeReport

This code is easier to read as a multiline If statement.

If NumEmployees < 10 Then
    BuildEmployeeReport
    ShowEmployeeReport
End If

One time when you must use a colon is when you execute certain commands interactively in the Debug or Immediate window. The Debug window executes one line at a time and keeps no past history to help with future commands. For example, it cannot remember a For statement and later match it to the corresponding Next statement. To execute a For loop in the Debug window, you must place the entire loop on a single line as in the following code:

For i = 1 To 10 : ?my_array(i) : Next i

Specify Lower Bounds for Arrays

When you declare an array without specifying its lower bound, it is not obvious what the array’s lower bound is. If you have a lot of experience with Visual Basic, you know that arrays usually start with an index of 0. Thus, the following statement allocates six array entries with indexes 0 through 5.

‘ Allocate 6 Person object references numbered 0 through 5.
Dim people(5) As Person

This is not obvious. The fact that the statement uses the value 5 to allocate six entries is confusing. Even worse, the file may include an Option Base statement that changes the default lower bound for arrays. While the Dim statement in the following code looks exactly like the previous one, it allocates only five array entries with indexes 1 through 5.

Option Explicit
Option Base 1
    :
‘ Much later...
‘Allocate 5 Person object references numbered 1 through 5.
Dim people(5) As Person

To make the code obvious, always explicitly specify a lower bound when you declare an array with bounds. The same principle applies when you resize an array using the ReDim statement.

‘ Allocate 5 Person object references numbered 1 through 5.
Dim people(0 To 5) As Integer

Dim jobs() As Integer
        :
    ‘ Resize the jobs array.
    ReDim jobs(0 To NumJobs)

Don’t Use Static Routines

In Visual Basic, if you declare a routine as static, all of the variables declared within the routine are allocated statically. For example, the following two subroutines are equivalent.

Static Private Sub MyStaticRoutine()
Dim i As Integer
Dim j As Integer
    :
End Sub

Private Sub MyStaticRoutine()
Static i As Integer
Static j As Integer
    :
End Sub

When you declare a routine as static, it is not obvious within the routine that the variables it contains are static. If the routine declares a lot of variables, a reader who looks at the last few variable declarations may not remember that they are all static.

Static Private Sub MyStaticRoutine()
Dim i As Integer
Dim j As Integer
Dim k As Integer
    :
Dim z As Integer

    :
End Sub


Previous Table of Contents Next


Products |  Contact Us |  About Us |  Privacy  |  Ad Info  |  Home

Use of this site is subject to certain Terms & Conditions, Copyright © 1996-1999 EarthWeb Inc.
All rights reserved. Reproduction whole or in part in any form or medium without express written permision of EarthWeb is prohibited.